package com.zkr.xml;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.util.List;

/**
 * @author Mayue
 * @date 2018/9/3 下午 2:39
 * @prodjec springboot_practice
 * @Modified by:
 */
public class Dom4jTest1 {
    public static void  main(String[] args) throws DocumentException {
        String path =Dom4jTest1.class.getResource("/email.xml").getPath();
        System.out.println(path);
        SAXReader reader=new SAXReader();
        Document doc=reader.read(path);
        Element email=doc.getRootElement();
//        f1(email);
//        f2(email);
        f3(email);

    }

    private static void f3(Element email) {
        for (int i=0;i<email.attributeCount();i++){
            Attribute attr=email.attribute(i);
            String n=attr.getName();
            String v=attr.getValue();
            System.out.println(n+"="+v);
        }
        //只包含文本
        if(email.isTextOnly()){
            System.out.println(email.getText());
            return;
        }
        for(int i=0;i<email.nodeCount();i++){
            Node n=email.node(i);
            if(n instanceof Element){
                f3((Element)n);
            }
        }
    }

    private static void f2(Element email) {
        System.out.println("-------------------");
        Element to =email.element("to");
        List<Element>list =to.elements("to-email");
        for (Element t:list) {
            System.out.println(t.getText());
        }
    }

    private static void f1(Element email) {
        String from=email.elementText("from");
        String subject=email.elementText("subject");
        String body=email.elementText("body");
        String date=email.attributeValue("date");
        String time=email.attributeValue("time");
        System.out.println(date);
        System.out.println(time);
        System.out.println(body);
        System.out.println(subject);
        System.out.println(from);
    }
}
